package com.example.vsprojekt;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Pattern;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Class that uses the webservice to show the lend books and to return books
 * @author Evgenij Pfafenrot
 *
 */
public class Ausgeliehene extends Activity {

	
	/** Called when the activity is first created. */
	private final String NAMESPACE = "http://makin8server.anydns.info:8181/";
	private final String URL = "http://makin8server.anydns.info:8181/catlib/services/WebService";
	private final String SOAP_ACTION2 = "http://makin8server.anydns.info:8181/MyBooks";
	private final String METHOD_NAME2 = "MyBooks";
	
	private final String NAMESPACE2 = "http://makin8server.anydns.info:8181/";
	private final String URL2 = "http://makin8server.anydns.info:8181/catlib/services/WebService";
	private final String SOAP_ACTION3 = "http://makin8server.anydns.info:8181/Returnbooks";
	private final String METHOD_NAME3 = "Returnbooks";
	
	private String TAG = "PGGURU";
	private static int id ; //student id
	TextView tv;
	String books;
	String erg;
	int status = 0;
	String ausgabe;
	BeschneideString bs = new BeschneideString();
	ListView listView ;
	
	/**
	 * method to show the lend books depending on the current student id
	 * @param id
	 */
	public void getMyBooks(int id) {
	    //Create request
	    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME2);
	    //Property which holds input parameters
	    PropertyInfo booksPI = new PropertyInfo();
	    //Set Name
	    booksPI.setName("Books");
	    //Set Value
	    booksPI.setValue(id);
	    //Set dataType
	    booksPI.setType(double.class);
	    //Add the property to request object
	    request.addProperty(booksPI);
	    //Create envelope
	    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
	    envelope.dotNet = true;
	    //Set output SOAP object
	    envelope.setOutputSoapObject(request);
	    //Create HTTP call object
	    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL,3000);
	 
	    try {
	        //Invole web service
	        androidHttpTransport.call(SOAP_ACTION2, envelope);
	        //Get the response
	        SoapObject result = (SoapObject) envelope.bodyIn;
	        //Assign it to fahren static variable
	        books = result.toString();
	        books = bs.cutFront(books, "=", 1);
	        books = bs.cutBack(books, ";", 1);   
	        if(books.equals("anyType{}")){
	        	books = "Keine Bücher gefunden";
	        }
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	}
	
	/**
	 * method to return a lend book
	 * @param book
	 */
	public void returnbook(String book) {
	
	    //Create request
	    SoapObject request = new SoapObject(NAMESPACE2, METHOD_NAME3);
	    //Property which holds input parameters
	    PropertyInfo booksPI = new PropertyInfo();
	    //Set Name
	    booksPI.setName("Books");
	    //Set Value
	    booksPI.setValue(book);
	    //Set dataType
	    booksPI.setType(double.class);
	    //Add the property to request object
	    request.addProperty(booksPI);
	    //Create envelope
	    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
	    envelope.dotNet = true;
	    //Set output SOAP object
	    envelope.setOutputSoapObject(request);
	    //Create HTTP call object
	    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
	 
	    try {
	        //Invoke web service
	        androidHttpTransport.call(SOAP_ACTION3, envelope);
	        //Get the response
	        SoapObject result = (SoapObject) envelope.bodyIn;
	        //Assign it to fahren static variable
	        erg = result.toString();
	        erg = bs.cutFront(erg, "=", 1);
	        erg = bs.cutBack(erg, ";", 1);   
            
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    
	}
	
	
	/**
	 * Allows to do a task in Background without using a Handler or Thread
	 * @author Evgenij Pfafenrot
	 *
	 */
	private class AsyncCallWS extends AsyncTask<String, Void, Void> {
        @Override
        protected Void doInBackground(String... params) {
            Log.i(TAG, "doInBackground"); //Send an INFO log message.
            if(status == 0){
            getMyBooks(id); //inner class method
            } else if(status ==1){
            	returnbook(ausgabe);
            }
			
            
            return null;
            
        }
 
        /**
         * method to get the books after getting a respond from the server
         */
        @Override
        protected void onPostExecute(Void result) {
            Log.i(TAG, "onPostExecute");
            if(books.equals("Keine Bücher gefunden")){
            	tv.setText(books.toString());
            }else {
            
            tv.setText("Ihre ausgeliehenen Bücher:");
            
            if(status ==1){
            Toast.makeText(getApplicationContext(), erg,Toast.LENGTH_LONG).show();
            }
            status = 0;
            String[] allbooks = books.split(Pattern.quote(","));
	        	ArrayAdapter<String> adapter = new ArrayAdapter<String>(Ausgeliehene.this, R.layout.list_item, allbooks);
            	listView.setAdapter(adapter); 
            	
            	listView.setOnItemClickListener(new OnItemClickListener() {
        			public void onItemClick(AdapterView<?> parent, View view,
        					int position, long id) {
  
        				String ausgabes = ((TextView)view).getText().toString();
        				ausgabe = bs.cutBack(ausgabes, "\n", 1);
        				
        				AlertDialog.Builder alert_box=new AlertDialog.Builder(Ausgeliehene.this);
        				alert_box.setIcon(R.drawable.icon);
        				alert_box.setMessage("Möchten Sie das Buch " + '"' +  ausgabe +  '"' + " wirklich zurückgeben?");
        				alert_box.setPositiveButton("Ja",new DialogInterface.OnClickListener() {
        				@Override
        				public void onClick(DialogInterface dialog, int which) {
        					status = 1; 
        					AsyncCallWS task = new AsyncCallWS(); //call method which should run in background
        		            //Call execute 
        		            task.execute();
        		            Intent intent = getIntent();
        		            finish();
        		            startActivity(intent);
        				
        				}
        				});
        				alert_box.setNegativeButton("Nein", new DialogInterface.OnClickListener() {
        				@Override
        				public void onClick(DialogInterface dialog, int which) {
        					status = 0;
        				}
        				});
        				alert_box.show();
        			}
        		});
            }  

           
        }
        
        /**
         * method called before getting a respond from the server
         */
        @Override
        protected void onPreExecute() {
            Log.i(TAG, "onPreExecute");
            tv.setText("Calculating...");
        }
 
        /**
         * method called before getting a respond from the server
         */
        @Override
        protected void onProgressUpdate(Void... values) {
            Log.i(TAG, "onProgressUpdate");
        }
 
    }
	
	/**
	 * Method that checks if the smartphone got an internet connection
	 * @return
	 */
	public boolean isOnline() {
	    ConnectivityManager cm =
	        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo netInfo = cm.getActiveNetworkInfo();
	    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
	        return true;
	    }
	    return false;
	}

	/**
	 * method called when the activity is loaded
	 */
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.ausgeliehene);
	    listView = (ListView) findViewById(R.id.mainListView);
	    tv = (TextView) findViewById(R.id.tv_result);
	                id = 80312; //student id
	                
	                if(this.isOnline()){
	                //Create instance for AsyncCallWS
	                AsyncCallWS task = new AsyncCallWS(); //ruft Methoden auf, die in Hintergrund ablaufen werden. 
	                //Call execute 
	                try {
						task.execute().get(4000,  TimeUnit.MILLISECONDS);
						
					} catch (InterruptedException e) {
						tv.setText("Webservice nicht erreichbar");
						task.cancel(true);
					} catch (ExecutionException e) {
						tv.setText("Webservice nicht erreichbar");
						task.cancel(true);					} catch (TimeoutException e) {
						tv.setText("Webservice nicht erreichbar");
						task.cancel(true);					}
	                
	                }else{
	                	tv.setText("WebService konnte nicht erreicht werden. Versuchen sie es später erneut");

	                }
	            }
	        
	}